package app.util;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by shadowedge on 2019/12/14.
 */
@Configuration
public class RestTemplateUtil {

    @LoadBalanced
    @Bean
    public RestTemplate okHttp() {
        OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)      //设置连接超时
            .readTimeout(10, TimeUnit.SECONDS)         //设置读超时
            .writeTimeout(60, TimeUnit.SECONDS)        //设置写超时
            .retryOnConnectionFailure(true)            //是否自动重连
            .connectionPool(
                    new ConnectionPool(
                            10,    // 10个并发连接
                            6,       // 6分钟空闲自动回收
                            TimeUnit.MINUTES))
            .build();
        // 使用OkHttp3构造restTemplate客户端
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory(client));
    }
}